package com.song.controller;


import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.song.Dto.MenuDto;
import com.song.base.consts.ResponseEnum;
import com.song.base.model.ResponseEntity;
import com.song.base.util.JwtTemplate;
import com.song.base.util.RedisKeys;
import com.song.domain.Menu;
import com.song.service.MenuService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单信息表 前端控制器
 * </p>
 *
 * @author Song
 * @since 2022-12-19
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Resource
    private MenuService menuService;
    @Resource
    private JwtTemplate jwtTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("getMenus")
    public ResponseEntity getMenuList(HttpServletRequest req){
        ResponseEntity<Object> responseEntity = new ResponseEntity<>();
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        //这里应该查询登录用户的
        String token = req.getHeader("token");
        if (StringUtils.isBlank(token)||"null".equals(token)){
            queryWrapper.le("power2", 1);
        }else {
            Claims claims = jwtTemplate.parseJwt(token);
            Integer uid = Integer.parseInt(claims.get("userId").toString());
            HashOperations<String, Object, Object> ops = stringRedisTemplate.opsForHash();
            Object userPower = ops.get(RedisKeys.USER_AUTH_USER + uid, "UserPower");
            if (userPower != null) {
                queryWrapper.le("power2", userPower);
            } else {
                queryWrapper.le("power2", 1);
            }
        }
        List<Menu> list = menuService.list(queryWrapper);
        List<MenuDto> menuDtoList=new ArrayList<>();
        for (Menu menu : list) {
            MenuDto menuDto = new MenuDto();
            BeanUtils.copyProperties(menu,menuDto);
            menuDtoList.add(menuDto);
        }
        responseEntity.setData(menuDtoList);
        responseEntity.setCode(ResponseEnum.RES_SUCCESS.getCode());
        responseEntity.setMsg("success");
        return responseEntity;
    }

}

